// components/VerificationCode/VerificationCode.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    mode: {
      type: String,
      value: 'mobile'
    },
    codeDevice: '',
  },
  observers: {
    'code': function (val) {
      if (val) {
        this.triggerEvent('code', {
          value: this.data.code,
        })
      }
    },
    'codeDevice': function (val) {
      if (val) {
        if ("mobile" === this.properties.mode) {
          if (getApp().util.isMobile(val)) {
            this.setData({
              isCanClick: true,
              action: getApp().api.mobileVerificationCode
            })
          } else {
            this.setData({
              isCanClick: false
            })
          }
        }
      } else {
        this.setData({
          isCanClick: false
        })
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    code: '',
    verificationCodeText: '获取验证码',
    action: '',
    isCanClick: false,
    timer: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleGetSmsCode() {
      if (this.data.isCanClick) {
        console.log(this.data.action)
        getApp().network.get(this.data.action, {
          [this.properties.mode]: this.data.codeDevice,
        }).then((res) => {
          if (res.code) {
            getApp().util.showToast('测试验证码：' + res.code)
          }

          var count = 120
          var timer = setInterval(() => {
            count--
            this.setData({
              verificationCodeText: (count + '后获取验证码'),
              isCanClick: false
            })
            if (count <= 0) {
              clearInterval(this.data.timer)
              this.setData({
                verificationCodeText: '获取验证码',
                isCanClick: true
              })
            }
          }, 1000)
          this.setData({
            timer: timer
          })
        }).catch((err) => {})

      }
    }
  }
})